//
//  SimpleTextInput.m
//  iPadMenuNew
//
//  Created by siloon on 4/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SLSimpleTextInput.h"

@interface SLSimpleTextInput()

@end

@implementation SLSimpleTextInput

@synthesize title = _title;
@synthesize tip = _tip;
@synthesize canCancel = _canCancel;
@synthesize delegate = _delegate;

- (id)initWithDelegate:(id<SLSimpleTextInputDelegate>)delegate
{
    self = [self init];
    if (self) {
		self.title = @"";
		self.tip = @"";
		self.canCancel = YES;
		self.delegate = delegate;
    }
    return self;
}

- (void)dealloc {
    self.title = nil;
	self.tip = nil;
	
    [super dealloc];
}

#pragma mark -

- (void)show{
	if(self.canCancel){
		alert = [[UIAlertView alloc] initWithTitle:@"" message:@"\n\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	}else{
		alert = [[UIAlertView alloc] initWithTitle:@"" message:@"\n\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	}
	alert.delegate = self;
	
	tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(12,40,260,25)];
	tipLabel.font = [UIFont systemFontOfSize:16];
	tipLabel.textColor = [UIColor whiteColor];
	tipLabel.backgroundColor = [UIColor clearColor];
	tipLabel.shadowColor = [UIColor blackColor];
	tipLabel.shadowOffset = CGSizeMake(0,-1);
	tipLabel.textAlignment = UITextAlignmentCenter;
	[alert addSubview:tipLabel];
	
	textField = [[UITextField alloc] initWithFrame:CGRectMake(16,80,252,25)];
	textField.font = [UIFont systemFontOfSize:18];
	textField.backgroundColor = [UIColor whiteColor];
	textField.delegate = self;
	[alert addSubview:textField];
	
	alert.title = self.title;
	tipLabel.text = self.tip;
	textField.text = @"";
	
	//[alert setTransform:CGAffineTransformMakeTranslation(0,109)];
	
	[alert show];
	
	[textField becomeFirstResponder];
	
	[tipLabel release];
	[textField release];
}

#pragma mark -

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
	
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
	[alert release];
	
	if(! self.canCancel || (self.canCancel && buttonIndex != alertView.cancelButtonIndex)){
		BOOL shouldDismiss = [self.delegate input:self shouldDismissWithText:textField.text];
		if(! shouldDismiss){
			[self show];
		}else{
			[self.delegate input:self didDismissWithText:textField.text];
		}
	}else{
		[self.delegate input:self didDismissWithText:textField.text];
	}
	
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	
}

- (BOOL)textFieldShouldReturn:(UITextField *)tf{
	[alert dismissWithClickedButtonIndex:alert.firstOtherButtonIndex animated:YES];
	
	return YES;
}

#pragma mark -


- (void)showWithTitle:(NSString *)title message:(NSString *)tip buttons:(BOOL)canCancel{
	
	self.title = title;
	self.tip = tip;
	self.canCancel = canCancel;
	
	[self show];
}

@end
